package apierr

import (
	"net/http"
	"sort"

	"github.com/gin-gonic/gin"

	"gitee.com/xuyiping_admin/pkg/grpcutil"
	"gitee.com/xuyiping_admin/pkg/xerr"
)

var (
	ignoreCodes = []int{400, 401, 404, 429}
	codesSize   = int(3)
)

// IgnoreStatusCodes ignore error with status codes
func IgnoreStatusCodes(codes ...int) {
	sort.Ints(codes)

	ignoreCodes = codes
	codesSize = len(codes)
}

func shouldIgnoreCode(code int) bool {
	// SearchInts using binary search, more fast
	idx := sort.SearchInts(ignoreCodes, code)
	return idx < codesSize && ignoreCodes[idx] == code
}

// ClassifiedAbort classify base on error type
func ClassifiedAbort(c *gin.Context, err error) {
	if err == nil {
		return
	}

	if e, isc := xerr.IsCustomError(err); isc {
		// 服务内部自定义错误
		AbortBadRequest(c, http.StatusBadRequest, e)
	} else if !grpcutil.FilterServerError(err) {
		// gRPC 部分错误
		AbortBadRequest(c, http.StatusBadRequest, err)
	} else {
		AbortError(c, err)
	}
}
